<?php
    class crud_take1
    {
        private $host = "127.0.0.1";
        private $user = "root";
        private $password = "";
        private $fields = array();
        private $fieldsLength = array();
        private $fieldsNumeric = array();
        private $database;
        private $table;
        
        public function setHost($host)
        {
            $this->host = $host;
        }
        public function setUser ($user)
        {
            $this->user = $user;
        }
        public function setPassword ($password)
        {
            $this->password = $password;
        }
        public function setDatabase ($database)
        {
            $this->database = $database;
            $this->con = mysqli_connect($this->host, $this->user, $this->password, $this->database);
            if(mysqli_connect_errno($this->con))
            {
                echo 'Error in connecting to database: ' . mysqli_connect_error();
            }
            else
            {
                return $this->con;
                echo 'Connection successfull to database ' . $this->database . ".<br/>";
            }
        }
        public function setTable ($table)
        {
            $this->table = $table;
        }
        
        public function connect()
        {
            $this->con = mysqli_connect($this->host, $this->user, $this->password, $this->database);
            if(mysqli_connect_errno($this->con))
            {
                echo 'Error in connecting to database: ' . mysqli_connect_error();
            }
            else
            {
                return $this->con;
                echo 'Connection successfull to database ' . $this->database . ".<br/>";
            }
        }
        /*
         * The read function
         * Used to display the table
         * Takes:
         *  parameter $sql, the query
         *  parameter $delete, false by default, set it to "true" if you want to display the delete button
         *  parameter $update, same as $delete
         */
        public function read($sql, $delete = false, $update = false)
        {
            $result = mysqli_query($this->con, $sql);
            if(!$result)
            {
                echo "Error in query: " . mysqli_error($this->con) . "<br/>";
            }
            else
            {
                $i = 0;
                //Get the names of the fields that the user wants to select
                while ($meta = mysqli_fetch_field($result)) {
                    if (!$meta) {
                        echo "No information available<br />\n";
                    }
                    $this->fields[$i] = $meta->name;
                    $this->fieldsLength[$i] = $meta->length;
                    $i++;
                }
                while ($this->selectRow = mysqli_fetch_array($result)){
                    
                    if(isset($_POST['update']) && !empty($_POST['update']) && ($_POST['hiddenUpdate'] == $this->selectRow[0])){
                        echo $this->fields[0] . ": " . $this->selectRow[$this->fields[0]]."<br/>";
                        echo "<form action='' method='post'>";
                        for($i=1;$i<count($this->fields);$i++){
                            echo "<input type='text' name='" . $this->fields[$i] . "' value='" . $this->selectRow[$this->fields[$i]] . "'/><br/>";
                        } 
                        echo "<input type='submit' name='save' value='Save'/><br/>";
                        echo "<input type='hidden' name='hiddenSave' value='" . $this->selectRow[0] . "'/>";
                        echo "</form>";
                    }else{
                        for($i=0;$i<count($this->fields);$i++){
                            echo $this->fields[$i] . ": " . $this->selectRow[$this->fields[$i]]."<br/>";
                        }
                        echo "<br/>";
                        if($delete === true && $update === true){
                            echo "<form action='' method='post'>" ;
                            echo     "<input type='hidden' name='hiddenUpdate' value='" . $this->selectRow[$this->fields[0]] . "'/>";
                            echo     "<input type='submit' name='update' value='Update'/>";
                            echo     "<input type='hidden' name='hiddenDelete' value='" . $this->selectRow[$this->fields[0]] . "'/>";
                            echo     "<input type='submit' name='delete' value='Delete'/>";
                            echo "</form>";
                        }else if($delete === true){
                            echo "<form action='' method='post'>" ;
                            echo     "<input type='hidden' name='hiddenDelete' value='" . $this->selectRow[$this->fields[0]] . "'/>";
                            echo     "<input type='submit' name='delete' value='Delete'/>";
                            echo "</form>";
                        }else if($update === true){
                            echo "<form action='' method='post'>" ;
                            echo     "<input type='hidden' name='hiddenUpdate' value='" . $this->selectRow[$this->fields[0]] . "'/>";
                            echo     "<input type='submit' name='update' value='Update'/>";
                            echo "</form>";
                        }
                    }
                }
            }
        }
        /*
         * We create a form trough which to insert a new row into the selected table
         * You can choose wether to allow the introduction of the id or not
         * The default is "no"
         */
        public function createPost($id = "false"){
            echo '<form action="" method="post">';
            if($id == "true"){
                echo '<input type="text" name="' . $this->fields[0] . '" placeholder="' . ucfirst($this->fields[0]) . '" />';
            }
            for($i=1;$i<count($this->fields);$i++)
            {
                if($this->fieldsLength[$i] > 120){
                    echo '<textarea rows="4" cols="30" placeholder="' . ucfirst($this->fields[$i]) . '"></textarea><br/>';
                }else{
                    echo '<input type="text" name="' . $this->fields[$i] . '" placeholder="' . ucfirst($this->fields[$i]) . '" /><br/>';
                }   
            }
            echo '<input type="submit" name="insert" value="Submit" />';
            echo '</form>';
        }
        
        public function insert(){
            $validImput = "true";
            if(isset($_POST['insert']) && !empty($_POST['insert'])){
                $localField = array(); 
                for($i=1;$i<count($this->fields);$i++){
                    $localField[$i] = mysql_escape_string($_POST[$this->fields[$i]]);
                    if(strpos($this->fields[$i], "mail") !== false){
                        $localField[$i] = filter_var($_POST[$this->fields[$i]],FILTER_VALIDATE_EMAIL);
                    }
//                    if(is_numeric($this->fieldsNumeric[$i])){
//                        $localField[$i] = filter_var($_POST[$localField[$i]],FILTER_VALIDATE_INT);
//                    }
                    if(!$localField[$i]){
                        echo "Please provide a valid " . $this->fields[$i] . ".<br/>"; 
                        $validImput = "false";
                    }
                }
                if($validImput == "true"){
                    $sqlInsert = "INSERT INTO $this->table(";
                    for($i=1;$i<count($this->fields);$i++){
                        if($i == (count($this->fields)-1)){
                            $sqlInsert .= "{$this->fields[$i]}";
                        }else{
                            $sqlInsert .= "{$this->fields[$i]},";
                        }   
                    }
                    $sqlInsert .= ")VALUES (";
                    for($i=1;$i<count($this->fields);$i++){
                        if($i == (count($this->fields)-1)){
                            $sqlInsert .= "'$localField[$i]'";
                        }else{
                            $sqlInsert .= "'$localField[$i]',";
                        }  
                    }
                    $sqlInsert .= ")";
                    $resultInsert = mysqli_query($this->con, $sqlInsert);

                    if(!$resultInsert)
                    {
                        echo mysqli_error($this->con) . ".<br/>";
                    }
                } 
                header("location:" . $_SERVER['PHP_SELF'] );
            }
        }
        public function delete(){
            if(isset($_POST['delete']) && !empty($_POST['delete'])){
                 $sqlDelete = "DELETE FROM " . $this->table . " WHERE id='" . $_POST['hiddenDelete'] . "'";
                       $resultDelete = mysqli_query($this->con, $sqlDelete);
                       if(!$resultDelete)
                       {
                           echo 'Error in query: ' . mysqli_error($this->con);
                       }
            header("location:" . $_SERVER['PHP_SELF'] );
            }
        }
        public function update(){
            $validImput = "true";
            if(isset($_POST['save']) && !empty($_POST['save']))
            {
                $localField = array(); 
                for($i=1;$i<count($this->fields);$i++){
                    $localField[$i] = mysql_escape_string($_POST[$this->fields[$i]]);
                    if(strpos($this->fields[$i], "mail") !== false){
                        $localField[$i] = filter_var($_POST[$this->fields[$i]],FILTER_VALIDATE_EMAIL);
                    }
                    if(!$localField[$i]){
                        echo "<p style=\"color:red\">Please provide a valid " . $this->fields[$i] . ".</p><br/>"; 
                        $validImput = "false";
                    }
                }
                if($validImput == "true")
                {
                    $sqlUpdate = "UPDATE " . $this->table . " SET "; 
                    for($i=1;$i<count($this->fields);$i++){
                        if($i == (count($this->fields)-1)){
                            $sqlUpdate .= $this->fields[$i] . "='" . $localField[$i] . "'";
                        }else{
                            $sqlUpdate .= $this->fields[$i] . "='" . $localField[$i] . "',";
                        }   
                    }
                    $sqlUpdate .= " WHERE id='" . $_POST['hiddenSave'] . "'";
                    $resultUpdate = mysqli_query($this->con, $sqlUpdate);
                    if(!$resultUpdate)
                    {
                        echo mysqli_errno($this->con);
                    }
                }
                header("location:" . $_SERVER['PHP_SELF'] );
            }
        }
    }
    $crud = new crud_take1;
    $crud->setDatabase("crud");
    $crud->setTable("users");
    $sql = "SELECT * FROM test";
    $crud->read($sql, true, true);
    $crud->createPost();
    $crud->insert();
    $crud->delete();
    $crud->update();
